// const host = 'http://blog.demo/api'
const host = 'http://word.xmfinger.com/apis/api'
const href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxca5e782125e89f46&redirect_uri=http://word.xmfinger.com&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect'

import $fly from 'flyio'
const request = async (options) => {
    if (typeof options === 'string') {
        options = {
            url: options
        }
    }

    options.url = host + '/' + options.url

    let response = await $fly.request(options.url, options.data, options)


    if (response.status === 500) {
        console.log("服务器错误")
    }

    return response
}

 const login = async (code) => {
    if (!code) {
        window.location.href = href
    }
    let authResponse = await $fly.post(
      host + "/authorizations",
      {code: code}
    )
    if (authResponse.status === 201) {
        await localStorage.setItem('access_token', authResponse.data.access_token)
        await localStorage.setItem('access_token_expired_at', new Date().getTime() + authResponse.data.expires_in * 1000)
    }

    return authResponse
}

const refreshToken = async (accessToken) => {
    try {
        let refreshTokenResponse = await $fly.request(
            host + '/' + 'authorizations/current',
            {},
            {
                headers: {'Authorization': 'Bearer ' + accessToken},
                method: "PUT"
            }
        )
        if (refreshTokenResponse.status === 200) {
            localStorage.setItem('access_token', refreshTokenResponse.data.access_token)
            localStorage.setItem('access_token_expired_at', new Date().getTime() + refreshTokenResponse.data.expires_in * 1000)
        }
        return refreshTokenResponse
    }
    catch (err) {
        if (err.status === 500) {
            localStorage.removeItem('access_token')
            localStorage.removeItem('access_token_expired_at')
            window.location.href = href
        }
    }
}

const getToken = async (options) => {
    let accessToken = localStorage.getItem('access_token')
    let expiredAt = localStorage.getItem('access_token_expired_at')

    if (accessToken && new Date().getTime() > expiredAt) {
        let refreshResponse = await refreshToken(accessToken)

        if (refreshResponse.status === 200) {
            accessToken = refreshResponse.data.access_token
        } else {
            let authResponse = await login()
            if (authResponse.status === 201) {
                accessToken = authResponse.data.access_token
            }
        }
    }
    return accessToken
}

const authRequest = async (options) => {
    if (typeof options === 'string') {
        options = {
            url: options
        }
    }

    let accessToken = await getToken()

 
    // 设置 token 在 header 中
    let headers = options.headers || {}
    headers.Authorization = 'Bearer ' + accessToken
    options.headers = headers

    try {
        let response = await request(options)
        return response
    } catch (err) {
        if (err.status === 401) {
            localStorage.removeItem('access_token')
            localStorage.removeItem('access_token_expired_at') 
            await login()
        }
        throw err
    }

}

const logout = async (params = {}) => {
    let accessToken = localStorage.getItem('access_token')

    let logoutResponse = await $fly.request(
      host + '/' + 'authorizations/current',
      {headers: {'Authorization': 'Bearer ' + accessToken}},
      {method: "delete"}
    )
    
    if (logoutResponse.status === 204) {
        WXP.clearStorage()
    }

    return logoutResponse
}

const checkLogin = async() => {
  let accessToken = localStorage.getItem('access_token')
  return accessToken
}

export default {
    login,
    authRequest,
    getToken,
    checkLogin,
    host
}
